package com.angel.core.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
/**
*@author '程千万'
*@createTime 2016年8月3日上午11:59:16
*@version 1.0
*/
public class PropertyConfUtil extends PropertyPlaceholderConfigurer {
	
	private Logger log = Logger.getLogger(PropertyConfUtil.class);
	private static Map<String , String> ctxPropertiesMap;
	
	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactory , Properties props) {
		// 解密加密配置
		try {
			List<String> list = new ArrayList<String>();
			list.add("database.username");
			list.add("database.password");
			list.add("database.url");
//			list.add("sys.username");
//			list.add("sys.password");
//			list.add("sys.url");
			decryptProperty(list , props);
		} catch (Exception e) {
			log.info("加密配置解密失败！");
			e.printStackTrace();
		}
		super.processProperties(beanFactory , props);
		ctxPropertiesMap = new HashMap<String , String>();
		for(Object key : props.keySet()) {
			String keyStr = key.toString();
			String value = props.getProperty(keyStr);
			ctxPropertiesMap.put(keyStr , value);
		}
	}
	
	public static String getContextProperty(String name) {
		return ctxPropertiesMap.get(name);
	}
	
	/**
	 * 对资源文件中指定的配置项进行解密
	 * 
	 * @param list
	 *            需要解密的配置项集合key
	 * @param props
	 *            资源文件
	 */
	private void decryptProperty(List<String> list , Properties props) {
		try {
//			System.out.println(props.getProperty("database.hostname"));
//			String modulus = props.getProperty("modulus");// 模
//			String private_exponent = props.getProperty("private_exponent");// 私钥指数
//			RSAPrivateKey priKey = RSAUtils.getPrivateKey(modulus , private_exponent);// 使用模和指数生成私钥
			for(String key : list) {
				String mi_value = props.getProperty(key);
//				String ming_value = RSAUtils.decryptByPrivateKey(mi_value , priKey);
				props.setProperty(key , mi_value);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
